
#ifndef UTILITY_H
#define UTILITY_H

#define DEVICENAME "eth1"

void GetSourceIP(std::string& srcAddr)
{
	int sd;
	sd = socket(AF_INET, SOCK_DGRAM, 0);
	struct ifreq ifr;
	strcpy(ifr.ifr_name, DEVICENAME);
	if((ioctl(sd, SIOCGIFADDR, (caddr_t)&ifr, sizeof(struct ifreq))) < 0)
		perror("GET IP ERROR: ");
	else
		srcAddr = std::string(inet_ntoa(((struct sockaddr_in*)(&(ifr.ifr_addr)))->sin_addr));

	close(sd);
}

/*
 * in_cksum --
 * Checksum routine for Internet Protocol
 * family headers (C Version)
 */
unsigned short in_cksum(unsigned short *addr, int len)
{
    register int sum = 0;
    u_short answer = 0;
    register u_short *w = addr;
    register int nleft = len;
    /*
     * Our algorithm is simple, using a 32 bit accumulator (sum), we add
     * sequential 16 bit words to it, and at the end, fold back all the
     * carry bits from the top 16 bits into the lower 16 bits.
     */
    while (nleft > 1)
    {
	  sum += *w++;
	  nleft -= 2;
    }
    /* mop up an odd byte, if necessary */
    if (nleft == 1)
    {
	  *(u_char *) (&answer) = *(u_char *) w;
	  sum += answer;
    }
    /* add back carry outs from top 16 bits to low 16 bits */
    sum = (sum >> 16) + (sum & 0xffff);		/* add hi 16 to low 16 */
    sum += (sum >> 16);				/* add carry */
    answer = ~sum;				/* truncate to 16 bits */
    return (answer);
}

void GetSourceMAC(unsigned char *my_MAC)
{
	int sd = socket(AF_INET, SOCK_DGRAM, 0);
	struct ifreq req;
	strcpy(req.ifr_name, DEVICENAME);
	int err = ioctl(sd, SIOCGIFHWADDR, &req);
	close(sd);
	if (err == -1)
	{	
		perror("GET MAC ERROR: ");
		exit(1);
	}
	memcpy(my_MAC, req.ifr_hwaddr.sa_data, 6);
}

int get_ifindex()
{
	int s;
	struct ifreq req;
	int err;
	strcpy(req.ifr_name, DEVICENAME);
	if((s = socket(AF_INET, SOCK_DGRAM,0))<0)
	{
		perror("GET IFINDEX SOCKET ERROR: ");
		exit(1);
	}
	err = ioctl(s, SIOCGIFINDEX, &req);
	close(s);
	if (err == -1)
	{
		perror("GET IFINDEX ERROR: ");
		exit(1);
	}
	return req.ifr_ifindex;
}

#endif // UTILITY_H
